/**
 * (created at 2011-1-14)
 */
package qiushuo.mysqlparser.ast.expression;

import qiushuo.mysqlparser.generator.SQLType;

/**
 * @author <a href="mailto:QiuShuo1985@gmail.com">QIU Shuo</a>
 */
public abstract class BinaryOperatorExpression implements Expression {
    protected final Expression leftOprand;
    protected final Expression rightOprand;
    protected final int precedence;

    public BinaryOperatorExpression(Expression leftOprand, Expression rightOprand, int precedence) {
        this.leftOprand = leftOprand;
        this.rightOprand = rightOprand;
        this.precedence = precedence;
    }

    public Expression getLeftOprand() {
        return leftOprand;
    }

    public Expression getRightOprand() {
        return rightOprand;
    }

    @Override
    public String generateSql(SQLType type) {
        switch (type) {
        case MySQL:
            StringBuilder sb = new StringBuilder();
            if (leftOprand.getPrecedence() < precedence) {
                sb.append('(').append(leftOprand.generateSql(type)).append(')');
            } else {
                sb.append(leftOprand.generateSql(type));
            }
            sb.append(' ').append(getOperator()).append(' ');
            if (rightOprand.getPrecedence() < precedence) {
                sb.append('(').append(rightOprand.generateSql(type)).append(')');
            } else {
                sb.append(rightOprand.generateSql(type));
            }
            return sb.toString();
        default:
            throw new UnsupportedOperationException("only mysql sql can be generated");
        }
    }

    @Override
    public int getPrecedence() {
        return precedence;
    }

    protected abstract String getOperator();
}
